package login

import (
    _"fmt"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    "qycms/models/auth"
    "qycms/untils"
)

type LoginController struct {
    beego.Controller
}

/**
 * 登录页面
 */
func (l *LoginController) Get()  {

    //验证码
    id,base64,err := untils.GetCaptcha()
    if err != nil {
        return
    }

    //模板
    l.Data["yzm"] = untils.Captcha{Id: id,Bs64: base64}
    l.TplName = "login/index.html"

}

/**
 *  登录验证操作
 */
func (l *LoginController) DoLogin() {

    //验证码
    captcha := l.GetString("captcha")
    captcha_id := l.GetString("captcha_id")
    isCaptcha := untils.VerityCaptcha(captcha_id,captcha)
    if !isCaptcha {
         l.Data["json"] = untils.Msg("验证码输入错误",1001);
         l.ServeJSON()
         l.StopRun()
    }

    //用户验证
    username := l.GetString("username")
    password := l.GetString("password")
    md5Pwd := untils.GetMd5Str(password)
    userInfo := auth.User{}

    o := orm.NewOrm()
    isexist := o.QueryTable("sys_user").Filter("username",username).Filter("password",md5Pwd).Exist()
    o.QueryTable("sys_user").Filter("username",username).Filter("password",md5Pwd).One(&userInfo)

    //逻辑判断
    if !isexist {
        l.Data["json"] = untils.Msg("用户名或密码错误",1002);
        l.ServeJSON()
        l.StopRun()
    }

    if userInfo.IsActive == 0 {
        l.Data["json"] = untils.Msg("该用户已停用，请联系管理员",1003);
        l.ServeJSON()
        l.StopRun()
    }


    l.Data["json"] = untils.Msg("登录成功",200);
    l.SetSession("uid",userInfo.Id)
    l.ServeJSON()
    l.StopRun()

}

/**
 *  点击图片刷新验证码
 */
func (l *LoginController) ChangeCaptcha(){

    id,base64,err := untils.GetCaptcha()

    if err != nil {
         l.Data["json"] = untils.Msg("生成验证码失败",404)
    }else{
        l.Data["json"] = untils.Captcha{Id:id,Bs64:base64,Code:200}
    }

    l.ServeJSON()

}